﻿#region

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

#endregion

namespace wsy.ext.Devlib.ExtensionMethods
{
   
    public static class TaskExt
    {
        public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
        {
            [ThreadStatic]
            private static bool _currentThreadIsProcessingItems;

            private readonly int _maxDegreeOfParallelism;

            private readonly LinkedList<Task> _tasks = new LinkedList<Task>();

            private int _delegatesQueuedOrRunning;

            public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
            {
                if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism));
                _maxDegreeOfParallelism = maxDegreeOfParallelism;
            }

            public sealed override int MaximumConcurrencyLevel => _maxDegreeOfParallelism;

            protected sealed override void QueueTask(Task task)
            {
                lock (_tasks)
                {
                    _tasks.AddLast(task);
                    if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
                    {
                        ++_delegatesQueuedOrRunning;
                        NotifyThreadPoolOfPendingWork();
                    }
                }
            }

            private void NotifyThreadPoolOfPendingWork()
            {
                ThreadPool.UnsafeQueueUserWorkItem(_ =>
                {
                    _currentThreadIsProcessingItems = true;
                    try
                    {
                        while (true)
                        {
                            Task item;
                            lock (_tasks)
                            {
                                if (_tasks.Count == 0)
                                {
                                    --_delegatesQueuedOrRunning;
                                    break;
                                }
                                item = _tasks.First.Value;
                                _tasks.RemoveFirst();
                            }
                            TryExecuteTask(item);
                        }
                    }
                    finally
                    {
                        _currentThreadIsProcessingItems = false;
                    }
                }, null);
            }

            protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
            {
                if (!_currentThreadIsProcessingItems) return false;
                if (taskWasPreviouslyQueued)
                    if (TryDequeue(task))
                        return TryExecuteTask(task);
                    else
                        return false;
                return TryExecuteTask(task);
            }

            protected sealed override bool TryDequeue(Task task)
            {
                lock (_tasks)
                {
                    return _tasks.Remove(task);
                }
            }

            protected sealed override IEnumerable<Task> GetScheduledTasks()
            {
                var lockTaken = false;
                try
                {
                    Monitor.TryEnter(_tasks, ref lockTaken);
                    if (lockTaken) return _tasks;
                    else throw new NotSupportedException();
                }
                finally
                {
                    if (lockTaken) Monitor.Exit(_tasks);
                }
            }
        }

        public static int TasksIsRunning(this IList<Task> ts)
        {
            return ts.Count - ts.Sum(task => task.IsCompleted ? 1 : 0);
        }

        public static int TasksIsRunning(this Task[] ts)
        {
            return ts.Length - ts.Sum(task => task.IsCompleted ? 1 : 0);
        }

        public static async Task<bool> TasksEachDo<T>(this IList<T> srcs, Func<T, Task> taskAction,int maxRunningTasks=5,int taskDelay=200,int timeOutMillisecond = 0)
        {
            List<Task> tasks = new List<Task>();
            Stopwatch sw = new Stopwatch();
            if (timeOutMillisecond>0)
            {
                sw.Start();
            }
            try
            {
               foreach (T src in srcs)
                {
                    if (timeOutMillisecond > 0)
                    {
                        sw.Stop();
                        TimeSpan sp = sw.Elapsed;
                        sw.Start();
                        if (sp.TotalMilliseconds > timeOutMillisecond)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    Task t = taskAction.Invoke(src);
                    tasks.Add(t);
                    while (true)
                    {
                        int running = TasksIsRunning(tasks);
                        if (running < maxRunningTasks ) break;
                        await Task.Delay(taskDelay);

                    }
                }
                while (TasksIsRunning(tasks) != 0)
                {
                    if (timeOutMillisecond > 0)
                    {
                        sw.Stop();
                        TimeSpan sp = sw.Elapsed;
                        sw.Start();
                        if (sp.TotalMilliseconds > timeOutMillisecond)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    await Task.Delay(taskDelay);
                }
            }
            catch (Exception)
            {
                return false;
            }
           
            return true;
        }
    }
}